from django.test import TestCase

import threading
import time
import smtplib
import datetime as dt
from email.mime.text import MIMEText
import  random


mailserver = "smtp.163.com"  #邮箱服务器地址
username_send = 'mlx1045579575@163.com'  #邮箱用户名
password = 'TLNOFJSYQPYWISOA'   #邮箱密码：需要使用授权码
#username_recv = '1045579575@qq.com'  #收件人，多个收件人用逗号隔开
list_num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
list_str = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 's', 't', 'x', 'y',
            'z']
veri_str = random.sample(list_str, 2)
veri_num = random.sample(list_num, 2)
veri_out = random.sample(veri_num + veri_str, 4)

def email_send(veri_res,username_recv,now_time):
    mail = MIMEText("验证码:" + veri_res + '\40\40\40\40\n发送时间:' + now_time)
    mail['Subject'] = '注册验证码:' + veri_res
    mail['From'] = "rasepberry"  # 发件人，注意这里，一定和smtp.sendmail参数一致，否则会报错
    mail['To'] = username_recv  # 收件人；[]里的三个是固定写法
    smtp = smtplib.SMTP(mailserver, port=25)  # 连接邮箱服务器，smtp的端口号是25

    try:
        smtp.login(username_send, password)  # 登录邮箱
        smtp.sendmail(username_send, username_recv, mail.as_string())  # 参数分别是发送者，接收者，第三个是把上面的发送邮件的内容变成字符串
        smtp.quit()  # 发送完毕后退出smtp TLNOFJSYQPYWISOA
        print("发送完毕")
    except:
        print("发送失败")

class MyThread (threading.Thread):
    def __init__(self, threadID,username_recv,veri_res,now_time):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.now_time = now_time
        self.username_recv = username_recv
        self.veri_res= veri_res
    def run(self):
        print ("开始线程 ID:"+self.threadID+ "收邮箱:"+self.username_recv)
        email_send(self.veri_res,self.username_recv, self.now_time)
        print ("退出线程：" + self.username_recv)




#邮箱验证码注册
def send_email(username_recv):
    print("发送验证码")
    now_time = dt.datetime.now().strftime('%F %T')
    veri_res = str(veri_out[0]) + str(veri_out[1]) + str(veri_out[2]) + str(veri_out[3])
    print("验证码：",veri_res)
    #email_send(veri_res,username_recv,now_time)
    print("开启线程发送")
    MyThread("111",username_recv,veri_res,now_time).start()
    return veri_res
#send_email("534604134@qq.com")